import { Drawer, Tooltip, message } from "antd";
import Modal from "../modal";
import React, { Component } from "react";
import "./ChatGroup.scss";
import Scrollbars from "react-custom-scrollbars";
import $, { data } from 'jquery';
import ChatGroupOne from "./group";
import fetch from "../../../util/fetch";
import {handleContactBook} from "../../../util/public";
const WorkCommunicationProxy = "api/Contact";
class ChatGroup extends Component {
  constructor(props) {
    super(props);
    this.state = { 
        selectUserList: [],
        searchResultVisible: false,
        searchList: [],
        forceHidden: true,
        groupName: "",
        keyword: "",
        unselectList: [],
        List: []
    };
  }
  componentDidMount(){
      let that = this;
      //控制搜素用户结果框的显隐
      document.addEventListener('click', function(e){
          if(($(e.target).attr('id') && $(e.target).attr('id').indexOf("search-user-input") !== -1) ||
         ($(e.target).attr('class') && ($(e.target).attr('class').indexOf("search-user-result") !== -1 ||
          $(e.target).attr('class').indexOf("search-user-li") !== -1)) ||
         ($(e.target).parent().attr('class') && 
         $(e.target).parent().attr('class').indexOf("search-user-li") !== -1)){
            that.setState({
                forceHidden: false
            })
          } else {
            that.setState({
                forceHidden: true
            })
          }
      })
      let SchoolID = sessionStorage.getItem("schoolId");
      let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      let UserID = userInfo.userId;
      let UserType = userInfo.userType;
      let schoolLevel = "S" + sessionStorage.getItem("schoolType");
      //获取初始目录
      let url =
      WorkCommunicationProxy +
      "/GetContactBook?SchoolID=" +
      SchoolID +
      "&UserID=" +
      UserID +
      "&UserType=" +
      UserType +
      "&SchoolLevel=" +
      schoolLevel;
      fetch
      .getWork({url})
      .then((res) => res.json())
      .then((json) => {
        if (json.StatusCode === 200) {
            let List = handleContactBook(json.Data)? handleContactBook(json.Data): {List: []};
            console.log(List);
            this.setState({
                List: List.List
            })
        }
      });
  }
  componentWillUpdate(){
      //将用户搜索结果列表一直显示在输入框下面
      if(!$('#search-user-input').offset() || !$('.drawer-body-left').offset()){
        return;
      }
      let {
          top,
          left
      } = $('#search-user-input').offset();
      let containerTop = $('.drawer-body-left').offset().top;
      let containerLeft = $('.drawer-body-left').offset().left;
      let containerWidth = $('.drawer-body-left').width();
      let containerHeight = $('.drawer-body-left').height();
      let newTop = top + 32;
      let newLeft = left;
      //设置最大x偏移量与最大y偏移量，让搜索结果框处于可视区域
      if(newTop - containerTop > containerHeight){
        newTop = containerHeight + containerTop + 10;
      }
      if(newLeft - containerLeft + 350 > containerWidth){
        newLeft = containerWidth + containerLeft - 351;
      }
      $('.search-user-result').css({
          top: newTop - containerTop,
          left: newLeft - containerLeft
      })
      
  }
  componentWillReceiveProps(nextProps){
      let {
          userList,
          visible,
          unselectList
      } = nextProps;
      let {
          selectUserList
      } = this.state;
      if(!Array.isArray(userList) || !visible){
          return;
      }
    //   if(userList.length === selectUserList.length){
    //       return;
    //   }
    let updateUserList = userList.filter((item)=>{
        return item.selectType == 2 || item.checkSign || item.userId;
    })
    updateUserList = updateUserList.map((item)=>{
        if(!item.UserID && item.selectId){
            item.UserID = item.selectId;
            item.UserName = item.selectName;
        }
        if(item.userId){
            item.UserID = item.userId;
            item.UserName = item.userName;
        }
        return item;
    })
    console.log(updateUserList)
    let list = selectUserList.concat(updateUserList);
    this.setState({
        selectUserList: list,
        unselectList: Array.isArray(unselectList)? unselectList: []
    })
  }
  selectUser = (data, type, kind) => {
    //type: 1为单个操作，2为多个操作
    //kind: add为添加, delete为删除
    let {
        selectUserList,
        unselectList
    } = this.state;
    if(unselectList.includes(data.UserID)){
        message.warn("该用户已经在审批人列表中，无法转交");
        return;
    }
    if(type == 1){
        if(kind == "add"){
            let targetIndex;
            selectUserList.forEach((item, index)=>{
                if(item.UserID === data.UserID){
                    targetIndex = index;
                }
            })
            if(targetIndex || targetIndex === 0){
                message.warn("该用户已被选择", 2);
                return;
            } else {
                selectUserList.push(data);
            }
            $('#search-user-input').val("");
            $('#search-user-input').focus();
        }
        if(kind == "delete"){
            let targetIndex;
            selectUserList.forEach((item, index)=>{
                if(item.UserID === data.UserID){
                    targetIndex = index;
                }
            })
            selectUserList.splice(targetIndex, 1);
        }
    }
    if(type == 2){
        if(kind == "add"){
            data.forEach((item)=>{
                let isExist = 0;
                selectUserList.forEach((child)=>{
                    if(item.UserID === child.UserID){
                        isExist = 1;
                    }
                })
                if(!isExist){
                    selectUserList.push(item);
                }
            })
            $('#search-user-input').val("");
            $('#search-user-input').focus();
        }
        if(kind == "delete"){
            data.forEach((item)=>{
                let targetIndex;
                selectUserList.forEach((child, index)=>{
                    if(item.UserID === child.UserID){
                        targetIndex = index;
                    }
                })
                if(targetIndex || targetIndex === 0){
                    selectUserList.splice(targetIndex, 1);
                }
            })
        }
    }
    //最多添加100位成员
    // if(selectUserList.length > 100){
    //     selectUserList.splice(100);
    //     message.warn(this.props.maxTip? this.props.maxTip: "最多添加100位成员~", 2);
    // }
    
    this.setState({
        selectUserList
    })
  }
  searchUser = (e) => {
      let {
          isCheck,
          unselectList
      } = this.props;
      let SchoolLevel = sessionStorage.getItem("schoolInfo")? JSON.parse(sessionStorage.getItem("schoolInfo")).SchoolLevel: "";
      let keyword = $(e.target).val();
      //为空时不搜索，搜索全部太慢，影响体验
      if(!keyword){
          return;
      }
      //http://IP:Port/api/Contact/SearchContact?schoollevel=S2&searchtype=0&keyword=搜索关键字
      let url = WorkCommunicationProxy +
      "/SearchContact?schoollevel=" + SchoolLevel +
      "&searchtype=0&keyword=" + keyword;
      fetch
      .getWork({url})
      .then((res)=>{
          return res.json();
      })
      .then((result)=>{
            if(result.StatusCode == 200 && Array.isArray(result.Data)){
                if(isCheck){
                    let dataList = [];
                    result.Data.forEach((item)=>{
                        if(item.UserType != 2 && item.UserType != 3){
                            dataList.push(item);
                        }
                    })
                    this.setState({
                        searchList: dataList,
                        forceHidden: false,
                        keyword
                    })
                    return;
                }
                this.setState({
                    searchList: result.Data,
                    forceHidden: false,
                    keyword
                })
            }
      })
  }
  setGroupName = (e) => {
    //设置讨论组名称
    let name = $(e.target).val();
    name = name.replace(/\\/g,"\\\\").replace(/"/g, `\\"`);
    this.setState({
        groupName: name
    })
  }
  returnSelect = () => {
      let {
          selectUserList
      } = this.state;
      let {
          count
      } = this.props;
      if(count && selectUserList.length > count){
          message.warn("最多只可选择" + count + "人！");
          return;
      }
      typeof this.props.getSelectList === "function" &&
      this.props.getSelectList(selectUserList);
      this.onClose();
  }
  createGroup = () => {
    //创建、编辑讨论组
    //http://IP:Port/api/Contact/OperateDiscussionGroup
    //"OperateFlag":1, //2 添加成员 1 新建讨论组   0 重命名讨论组  -1 解散讨论组  -2退出讨论组  -3删除某位成员(只有讨论组拥有者才能删除成员)
    //"GroupID": "FC257086-346B-42C2-BF56-931E4D9318C7",  //讨论组ID  新建讨论组时 传空“”
    //"GroupName": "重命名Tea001新建讨论组1",  //讨论组名称
    //"GroupMemberIDs": "Tea001,Tea002,Tea003,Tea004,Stu001"  //讨论组成员ID串，用英文逗号 , 分割 
    //包含UserID 自身  重命名及解散时 此字段传空 ；删除某位成员时，这里传要删除的成员ID  一次只能删除一个
    let {
        groupName,
        selectUserList
    } = this.state;
    let {
        isEdit,
        currentGroup
    } = this.props;
    let UserID = JSON.parse(sessionStorage.getItem("userInfo")).UserID;
    if(!groupName){
        message.warn("讨论组名称不能为空", 2);
        return;
    }
    if(selectUserList.length === 0){
        message.warn("讨论组成员不能为空", 2);
        return;
    }
    let memberIDs = selectUserList.map((item)=>{
        return item.UserID;
    })
    //创建讨论组需要包含自身在内
    if(!memberIDs.includes[UserID]){
        memberIDs.push(UserID);
    }
    let url = WorkCommunicationProxy +
    "/OperateDiscussionGroup";
    fetch
    .post({url, body: {
        OperateFlag: isEdit? 2: 1,
        GroupID: isEdit? currentGroup.GroupID: "",
        GroupName: groupName,
        GroupMemberIDs: memberIDs.join(",")
    }})
    .then((res)=>{
        return res.json();
    })
    .then((result)=>{
        if(result.StatusCode == 200 && result.Data === 1){
            this.onClose();
        }
    })
  }
  onClose = () => {
      //关闭抽屉时将数据还原成初始状态
      console.log("asdweq")
      this.setState({
        selectUserList: [],
        searchResultVisible: false,
        searchList: [],
        forceHidden: true,
        groupName: "",
        groupID: ""
      });
      typeof this.props.onClose === "function" &&
      this.props.onClose();
      typeof this.props.changeVisible === "function" &&
      this.props.changeVisible(false);
  }
  render() {
      let {
        drawerVisible,
        onClose,
        isEdit,
        changeVisible,
        currentGroup,
        isCheck,
        noMe,
        ...other
      } = this.props;
      let UserID = sessionStorage.getItem("userId");
      let {
        selectUserList,
        searchResultVisible,
        searchList,
        forceHidden,
        keyword,
        unselectList,
        List
      } = this.state;
      return (
        <Modal
        className="drawer-container"
        width={900}
        title={"选择对象"}
        height={592}
        noFooter={true}
        onCancel={this.onClose}
        changeVisible={changeVisible}
        visible={drawerVisible}
        destroyOnClose={true}
        {...other}>
            {/* <div className="drawer-top">{"选择对象"}</div> */}
            <div className="drawer-body">
                <div className="drawer-body-left">
                    <ul className="search-user-result">
                        <Scrollbars
                        autoHeight
                        autoHeightMax={150}>
                            {
                                forceHidden?
                                "":
                                searchList.length > 0?
                                searchList.map((item, index)=>{
                                    let updateName = item.UserName.split('');
                                    updateName = updateName.map((child)=>{
                                        if(child === keyword){
                                            child = <span style={{color: '#ff6600'}}>{child}</span>
                                        }
                                        return child;
                                    })
                                    let updateID = item.UserID.split('');
                                    updateID = updateID.map((child)=>{
                                        if(child === keyword){
                                            child = <span style={{color: '#ff6600'}}>{child}</span>
                                        }
                                        return child;
                                    })
                                    if(noMe && item.UserID === UserID){
                                        return;
                                    }
                                    return (
                                        <li 
                                        key={index} 
                                        title={item.UserName + "(" + item.UserID + ")"}
                                        className={`search-user-li ${unselectList.includes(item.UserID)? "disable": ""}`}
                                        onClick={()=>this.selectUser(item, 1, "add")}>
                                            <img src={item.PhotoPath} alt="用户头像" />
                                            {updateName}
                                            <span style={{color: "#999999"}}>({updateID})</span>
                                        </li>
                                    )
                                }):
                                <div style={{
                                    height: "40px",
                                    lineHeight: "40px",
                                    textAlign: "center",
                                    color: "#666666",
                                }}>暂无搜索结果</div>
                            }
                        </Scrollbars>
                    </ul>
                    <div className="selected-user">
                        <Scrollbars>
                            {
                                selectUserList.map((item, index)=>{
                                    return (
                                        <div 
                                        key={index} 
                                        className="user-one"
                                        title={item.UserName + "(" + item.UserID + ")"}>
                                            {item.UserName}
                                            <span style={{color: "#999999"}}>({item.UserID})</span>
                                            <i 
                                            className="user-one-cancel" 
                                            onClick={()=>this.selectUser(item, 1, "delete")}></i>
                                        </div>
                                    )
                                })
                            }
                            <input 
                            type="text" 
                            id="search-user-input" 
                            placeholder="搜索..." 
                            // maxLength={12}
                            autocomplete="off"
                            onChange={this.searchUser} 
                            />
                        </Scrollbars>
                    </div>
                    <div className="line"></div>
                    {/* <div className="group-name">
                        讨论组名称: 
                        {
                            isEdit?
                            <input 
                            type="text"
                            value={currentGroup.GroupName}
                            className="name-input" 
                            readOnly={true}
                            maxLength={20}/>:
                            <input 
                            type="text"
                            className="name-input" 
                            onChange={this.setGroupName}
                            maxLength={20}/>
                        }
                    </div> */}
                    <div className="group-setting">
                        <div className="group-btn">
                            <div className="confirm-btn" onClick={this.returnSelect}>
                                确认
                                {selectUserList.length > 0? "(已选" + selectUserList.length + "人)": ""}
                            </div>
                            <div className="cancel-btn" onClick={this.onClose}>取消</div>
                        </div>
                    </div>
                </div>
                <div className="drawer-body-right">
                    <Scrollbars>
                        <ul className="contact-list">
                            
                            {
                                List.map((item, index)=>{
                                    //隐藏讨论组、最近联系人、常用联系人
                                    if(item.value == 11 || item.value == 1 || item.value == 3){
                                        return;
                                    }
                                    return (
                                        <ChatGroupOne 
                                        data={item} 
                                        key={index}
                                        isCheck={isCheck}
                                        noMe={noMe}
                                        unselectList={unselectList || []}
                                        selectUserList={selectUserList}
                                        selectUser={this.selectUser}
                                        ></ChatGroupOne>
                                    )
                                })
                            }
                            
                        </ul>
                    </Scrollbars>
                </div>
            </div>
        </Modal>
      )
  }
}
export default ChatGroup;